package com.nulldev.util.crypto.api2.encryptors;

import java.math.BigInteger;
import java.nio.charset.Charset;

import com.nulldev.util.crypto.api2.Cryptable;
import com.nulldev.util.crypto.api2.EncryptionUtil;
import com.nulldev.util.crypto.api2.EncryptionUtil.Types;

public class P2PC extends Cryptable{

	public P2PC() {
		super("p2pC");
	}

	@Override
	public String encrypt(final String object, final String pass) {
		final int passLength = pass.length();
		final String iteration1 = EncryptionUtil.byType(Types.XOR).encrypt(object, pass);
		final String iteration2 = EncryptionUtil.byType(Types.Blowfish).encrypt(iteration1, pass);
		return iteration2;
	}

	@Override
	public String decrypt(final String object, final String pass) {
		final int passLength = pass.length();
		final String iteration1 = object;
		final String iteration2 = EncryptionUtil.byType(Types.Blowfish).decrypt(iteration1, pass);
		final String iteration3 = EncryptionUtil.byType(Types.XOR).decrypt(iteration2, pass);
		return iteration3;
	}

    public String toHexString(byte[] bytes) {
    	final StringBuilder sb = new StringBuilder();
     	for (byte b : bytes) {
     		sb.append(String.format("%02X", b));
     	}
     	return sb.toString();
    }
    
	@Override
	public String encrypt(String object, String pass, Charset charset) {
		final int passLength = pass.length();
		final String iteration1 = EncryptionUtil.byType(Types.XOR).encrypt(object, pass, charset);
		final String iteration2 = EncryptionUtil.byType(Types.Blowfish).encrypt(iteration1, pass, charset);
		return iteration2;
	}

	@Override
	public String decrypt(String object, String pass, Charset charset) {
		final int passLength = pass.length();
		final String iteration1 = object;
		final String iteration2 = EncryptionUtil.byType(Types.Blowfish).decrypt(iteration1, pass, charset);
		final String iteration3 = EncryptionUtil.byType(Types.XOR).decrypt(iteration2, pass, charset);
		return iteration3;
	}
    
    public String toHex(String arg) {
        return String.format("%02x", new BigInteger(1, arg.getBytes(/*YOUR_CHARSET?*/)));
    }
    
    public String toHex(final String arg, final Charset charset) {
        return String.format("%02x", new BigInteger(1, arg.getBytes(charset)));
    }
    
    public byte[] toByteArray(String s) {
    	int len = s.length();
     	byte[] data = new byte[len / 2];
     	for (int i = 0; i < len; i += 2) {
     		data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i + 1), 16));
     	}
     	return data;
    }
    
    public static String unHex(String arg) {        
        String str = "";
        for(int i=0;i<arg.length();i+=2)
        {
            String s = arg.substring(i, (i + 2));
            int decimal = Integer.parseInt(s, 16);
            str = str + (char) decimal;
        }       
        return str;
    }
}
